<?php

declare(strict_types=1);

namespace App\Middleware;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpMessage\Stream\SwooleStream;
use App\Exception\ValidateException;
use App\Utils\Jwt;


class JwtAuthMiddleware implements MiddlewareInterface
{
	
	/**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;
	

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }
	
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
		$token = $this->request->header('Authorization');
		if(empty($token)){
			throw new ValidateException("token不能为空");
		}
		
		$jwt = Jwt::getInstance();
		$jwt->setIss(config('my.jwt_iss'))->setAud(config('my.jwt_aud'))->setSecrect(config('my.jwt_secrect'))->setToken($token);

		if($jwt->validationToken()){
			$info = json_decode($jwt->decode(),true);
			if($info){
				foreach($info as $k=>$v){
					$this->request->$k = $v;
				}
			}
			return $handler->handle($request);
		}else{
			throw new ValidateException("token错误",config('my.jwtErrorCode'));
		}
    }
    
} 